package com.vmc;

import java.io.File;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.vmc.exception.VMCException;
import com.vmc.strategy.Action;
import com.vmc.strategy.CleanupAction;
import com.vmc.strategy.RenameTransferAction;
import com.vmc.strategy.TransferAction;
import com.vmc.util.DirectoryTraversalUtility;
import com.vmc.util.ErrorPropertiesUtility;
import com.vmc.util.GlobalStorageUtility;
import com.vmc.util.SingleInstanceUtility;

public class DownloadTransfer {
	
	// @TODO: include subtitles for movies
	
	static Logger logger = LogManager.getLogger(DownloadTransfer.class);

	public static final String CODE = "download_transfer";
	public static final String PROPERTIES_FILE = "./app.properties"; 
	public static final String ALTERNATE_PROPERTIES_FILE = "./app/config/app.properties"; 
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			(new DownloadTransfer()).runApp();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void runApp() throws VMCException {
		logger.info("Running Download transfer.");
		logger.info("Loading Error properties...");
		ErrorPropertiesUtility.getInstance().load();
		logger.info("Done!");
		
		logger.info("Checking for other running instances...");
		if (SingleInstanceUtility.getInstance().isInstanceExisting(CODE)) {
			throw new VMCException(VMCException.APP_RUNNING);
		}
		logger.info("Done!");
		
		logger.info("Creating instance file...");
		SingleInstanceUtility.getInstance().ensureSingleInstance(CODE);
		logger.info("Done!");
		
		// load global details 
		GlobalStorageUtility.getInstance().initialize();
		
		// traverse the directory 
		Action<File> mainAction = new TransferAction(); 
		Action<File> postAction = new RenameTransferAction();
		postAction.chainedTo(new CleanupAction());
		DirectoryTraversalUtility.getInstance().traverseDirectory(GlobalStorageUtility.getInstance().getProperties().getSourceDirectory(), mainAction, null, postAction);

		
		logger.info("Removing instance file...");
		SingleInstanceUtility.getInstance().endSingleInstance(CODE);
		logger.info("Done!");
		logger.info("Done running Download transfer.");
	}
}
